import {
  CourseEntry,
  CourseWatchEntity,
  RedPacketData,
  RewardData,
  InviteCheckError,
  OnlineCountResponse
} from "@/typings/course";
import { http } from "@/utils/http";
import { defineStore } from "pinia";
import { ref, computed, onMounted, onUnmounted, watch } from "vue";
import { useLocationParams } from "@/store/useLocationStore";
import { usePlayerStore } from "./usePlayer";
import { launchRedPacket3Times } from "./useRedPacket";
import dayjs from "dayjs";
import { getRandomInterval } from "@/utils/timer";
import { parseUserAgent } from "@/utils/wechat";
import { showToast } from "vant";
import { useUserStore } from "./useUserStore";

// 只保留显示相关的逻辑
export const useCourseCountdown = defineStore("countdown", () => {
  const store = useCourseData();

  // 格式化显示
  const formattedDays = computed(() =>
    Math.floor(store.remainingTime / (1000 * 3600 * 24))
      .toString()
      .padStart(2, "0")
  );

  const formattedHours = computed(() =>
    Math.floor((store.remainingTime % (1000 * 3600 * 24)) / (1000 * 3600))
      .toString()
      .padStart(2, "0")
  );

  const formattedMinutes = computed(() =>
    Math.floor((store.remainingTime % (1000 * 3600)) / (1000 * 60))
      .toString()
      .padStart(2, "0")
  );

  const formattedSeconds = computed(() =>
    Math.floor((store.remainingTime % (1000 * 60)) / 1000)
      .toString()
      .padStart(2, "0")
  );

  // 开始时间显示
  const startTime = computed(() => {
    const date = store.initialDate;
    if (!date) {
      return "";
    }
    return `${date.getFullYear()}-${(date.getMonth() + 1)
      .toString()
      .padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")} ${date
      .getHours()
      .toString()
      .padStart(2, "0")}:${date
      .getMinutes()
      .toString()
      .padStart(2, "0")}:${date.getSeconds().toString().padStart(2, "0")}`;
  });

  return {
    formattedDays,
    formattedHours,
    formattedMinutes,
    formattedSeconds,
    startTime
  };
});

// 包含数据和动态逻辑
export const useCourseData = defineStore("courseData", () => {
  const { getParam, setParam } = useLocationParams();
  const courseData = ref<CourseEntry | null>(null);
  const courseWatchData = ref<CourseWatchEntity | null>(null);
  const loading = ref(false);
  const error = ref(null);
  const remainingTime = ref(0);
  const isCountdownFinished = ref(false);
  let animationFrameId: number | null = null;
  const redPacketList = ref<RedPacketData[] | null>(null);
  const shareUserId = ref(null);
  const userStore = useUserStore();
  // setParam("shareUserId", userStore.user.buyerUserId.toString());
  let lastTime = 0;
  // 初始时间计算
  const initialDate = computed(() => {
    if (courseData.value) {
      return new Date(courseData.value.openStartTime);
      // return new Date(Date.now() + 1000 * 1);
    }
    return null;
  });
  const getRedPacketList = async () => {
    try {
      const data = await http.request<RedPacketData[]>({
        url: "/screening/reward-record",
        method: "POST",
        data: { ...roomParams.value }
      });
      redPacketList.value = data;
    } catch (error) {}
  };
  const checkInviteCode = async inviteCode => {
    try {
      const data = await http.request<InviteCheckError>({
        url: "/screening/entryBefore",
        method: "POST",
        data: {
          inviteCode: inviteCode
          // inviteCode: 166
        }
      });
      return data;
    } catch (error) {
      console.error("Error checking invite code:", error);
      // router.push({ name: "Error", query: { message: "邀请码错误" } });
    }
  };

  // 检查倒计时状态
  const checkCountdownStatus = () => {
    if (!initialDate.value) return;

    const now = Date.now();
    remainingTime.value = Math.max(initialDate.value.getTime() - now, 0);

    // 如果初始时就已经结束，直接设置状态
    if (remainingTime.value === 0) {
      isCountdownFinished.value = true;
      return true;
    }
    return false;
  };

  // 倒计时更新逻辑
  const updateRemaining = (timestamp: number) => {
    if (!initialDate.value) {
      return;
    }

    // 控制更新频率为 1s
    if (timestamp - lastTime >= 1000) {
      const now = Date.now();
      remainingTime.value = Math.max(initialDate.value.getTime() - now, 0);
      lastTime = timestamp;

      // 检查倒计时是否结束
      if (remainingTime.value === 0) {
        isCountdownFinished.value = true;
        stopTimer();
        return;
      }
    }

    // 继续动画
    animationFrameId = requestAnimationFrame(updateRemaining);
  };

  // 启动倒计时
  const startTimer = () => {
    // 停止可能存在的动画
    if (animationFrameId) {
      cancelAnimationFrame(animationFrameId);
    }
    // 重置时间戳
    lastTime = 0;
    // 启动动画
    animationFrameId = requestAnimationFrame(updateRemaining);
  };

  // 停止倒计时
  const stopTimer = () => {
    if (animationFrameId) {
      cancelAnimationFrame(animationFrameId);
      animationFrameId = null;
    }
  };
  // 课程是否准备就绪
  const courseReady = computed(
    () => courseData.value !== null && isCountdownFinished.value
  );

  // 获取课程数据
  const entryRoom = async roomId => {
    loading.value = true;
    try {
      // const res = await fetch("/public/data/Course.json");
      // const json = await res.json();
      // courseData.value = json.data;
      const data = await http.request<CourseEntry>({
        url: "/screening/entry",
        headers: { application: "json" },
        method: "POST",
        data: {
          ...roomParams.value,
          roomId: roomId,
          shopId: getParam("shopId"),
          dealId: getParam("dealerId")
        }
      });
      if (!data) return;
      data.openStartTime = dayjs(data.openStartTime).toISOString();
      data.openEndTime = dayjs(data.openEndTime).toISOString();
      courseData.value = data;

      // 先检查倒计时状态
      if (!checkCountdownStatus()) {
        // 只有在倒计时未结束时才启动定时器
        startTimer();
      }
      return data;
    } catch (err: any) {
      error.value = err;
      console.error(err);
    } finally {
      loading.value = false;
    }
  };

  const watchCourse = async (roomId = courseData.value.roomId) => {
    loading.value = true;
    try {
      const data = await http.request<CourseWatchEntity>({
        url: "/screening/watch",
        headers: { application: "json" },
        method: "POST",
        data: {
          roomId: roomId,
          shopId: getParam("shopId"),
          dealId: getParam("dealerId"),
          shareUserId: shareUserId.value,
          ...roomParams.value
        }
      });
      courseWatchData.value = data;
    } catch (err: any) {
      error.value = err;
      console.error(err);
    } finally {
      loading.value = false;
    }
  };

  const recordAnswerAttempt = async () => {
    loading.value = true;
    try {
      await http.request({
        url: "/screening/record-answer",
        headers: { application: "json" },
        method: "POST",
        data: {
          ...roomParams.value
        }
      });
    } catch (err: any) {
      error.value = err;
      console.error(err);
    } finally {
      loading.value = false;
    }
  };

  const playerStore = usePlayerStore();
  const onPlayeEnd = async () => {
    endOnlineUpdater();
    if (courseWatchData.value.isCompleted) {
      return;
    } else {
      try {
        const data = await http.request({
          url: "/screening/completed",
          method: "POST",
          data: roomParams.value
        });
        if (data) {
          courseWatchData.value.isCompleted = 1;
        }
      } catch (error) {}
    }
    setTimeout(() => {
      location.reload();
    }, 1000);
  };
  watch(() => playerStore.isPlayerEnd, onPlayeEnd);
  watch(
    () => courseWatchData.value?.isCompleted,
    isCompleted => {
      if (isCompleted) {
        playerStore.setControlsEnabled(true);
      }
    }
  );
  // 重置倒计时
  const resetTimer = () => {
    stopTimer();
    remainingTime.value = 0;
    lastTime = 0;
    isCountdownFinished.value = false;
  };
  const roomParams = computed(() => ({
    roomId: courseData.value?.roomId,
    watchRecordId: courseWatchData.value?.watchRecordId,
    roomType: courseData.value?.roomType,
    inviteCode: getParam("inviteCode"),
    screeningId: courseData.value?.screeningId,
    subjectId: getParam("scene") == "0" ? getParam("sId") : getParam("sRId")
  }));

  const addComplain = async _data => {
    try {
      const data = await http.request({
        url: "/subject/complaints/save",
        method: "POST",
        data: { ...roomParams.value, ..._data }
      });
      return data;
    } catch (error) {}
  };
  const answer = async (answerState: number) => {
    try {
      const data = await http.request({
        url: "/screening/answer",
        method: "POST",
        data: { ...roomParams.value, answerState }
      });
      courseWatchData.value.answerRewardState = answerState;
      courseWatchData.value.isAnswer = 1;
      return data;
    } catch (error) {
      console.error("Error during answer:", error);
    }
  };
  const signin = async () => {
    try {
      const data = http.request({
        url: "/screening/sign",
        method: "POST",
        data: roomParams.value
      });
      return data;
    } catch (error) {
      console.error("Error during sign-in:", error);
    }
  };

  const sendPullState = async (pullState: number, sn: string) => {
    try {
      const { os, device, browser, wechat, network } = parseUserAgent();
      const data = await http.request({
        url: "/screening/reward/pull-state",
        method: "POST",
        data: {
          pullState,
          sn,
          sysVersion: JSON.stringify(os),
          browerVersion: JSON.stringify(browser),
          wechatVersion: JSON.stringify(wechat)
        }
      });
      return data;
    } catch (error) {}
  };

  const reward = async rewardType => {
    try {
      const data = await http.request<RewardData>({
        url: "/screening/reward",
        method: "POST",
        data: {
          ...roomParams.value,
          rewardType,
          shopId: getParam("shopId"),
          dealId: getParam("dealerId"),
          totalDuration: playerStore.maxProgress
        }
      });
      if (data) {
        const {
          sn,
          packageInfo,
          message = "单据信息缺失，请稍后再试",
          bizCode
        } = data;
        if (!packageInfo || !sn) {
          showToast(message);
          return;
        }
        if (bizCode !== "SUCCESS") {
          showToast(message);
          return;
        }
        launchRedPacket3Times({
          packageInfo,
          sn,
          sendPullState,
          callback: () => {}
        });
      }
      return data;
    } catch (error) {
      console.error("Error during reward:", error);
    }
  };

  const updateOnline = async (onlineDuration?) => {
    try {
      const data: any = await http.request<OnlineCountResponse>({
        url: "/screening/online",
        method: "POST",
        data: { ...roomParams.value, onlineDuration }
      });
      courseWatchData.value.onlineCount = data.onlineCount;
    } catch (error) {}
  };
  // Watch for courseReady changes
  if (courseReady.value) {
    onCourseReady();
  }
  watch(courseReady, async isReady => {
    if (isReady) {
      onCourseReady();
    }
  });
  async function onCourseReady() {
    try {
      const { getParam, setParam } = useLocationParams();
      if (!shareUserId.value) {
        setShareUserId(getParam("shareUserId"));
      }
      setParam("shareUserId", userStore.user.buyerUserId.toString());
      await watchCourse(courseData.value.roomId);
      // 课程准备就绪后，调用在线接口
      startOnlineUpdater();
      // await goOnline()
    } catch (error) {}
  }
  let onlineTimer;
  const startOnlineUpdater = () => {
    let randomInterval;
    const scheduleNextUpdate = () => {
      if (onlineTimer) {
        updateOnline(randomInterval);
      }
      randomInterval = getRandomInterval();
      onlineTimer = setTimeout(scheduleNextUpdate, randomInterval * 1000);
    };

    scheduleNextUpdate();
  };
  const endOnlineUpdater = () => {
    if (onlineTimer) {
      clearTimeout(onlineTimer);
    }
  };
  // 组件卸载时清理
  onUnmounted(() => {
    stopTimer();
    endOnlineUpdater();
  });

  const setShareUserId = userId => {
    shareUserId.value = userId;
  };

  return {
    endOnlineUpdater,
    stopTimer,
    courseData,
    courseWatchData,
    loading,
    error,
    entryRoom,
    courseReady,
    remainingTime,
    initialDate,
    isCountdownFinished,
    resetTimer,
    checkInviteCode,
    signin,
    reward,
    watchCourse,
    recordAnswerAttempt,
    getRedPacketList,
    redPacketList,
    addComplain,
    answer,
    roomParams,
    sendPullState,
    setShareUserId,
    shareUserId
  };
});

export const useCourseSignin = defineStore("courseSignin", () => {
  const courseStore = useCourseData();
  const playerStore = usePlayerStore();
  const loading = ref(true);
  const timesToSign = computed(() =>
    courseStore.courseData?.sign.signInRule
      .split(",")
      .map(str => parseFloat(str))
  );
  const isVisible = ref(false);
  const isCompleted = ref(false);
  const setIsCompleted = (value: boolean) => {
    isCompleted.value = value;
  };
  const setIsVisible = (value: boolean) => {
    isVisible.value = value;
  };
  if (courseStore.courseWatchData?.isCompleted == 0) {
    watch(
      () => playerStore.maxProgress, //播放过程中
      (maxProgress, oldMaxProgress) => {
        console.log(maxProgress);
        if (isVisible.value || courseStore.courseData?.sign.openSignIn !== 1) {
          return;
        }
        if (maxProgress) {
          // 检测是否需要签到
          timesToSign.value.find(signMin => {
            if (
              signMin * 60 == Math.floor(maxProgress) &&
              signMin * 60 != Math.floor(oldMaxProgress) // 避免重复触发
            ) {
              // if (signMin == Math.floor(maxProgress)) {
              // loading.value = false;
              console.log("open signin");
              setIsVisible(true);
              return true;
            }
          });
          // 检测捡到结束是否需要发红包
          if (isALlSignined(courseStore.courseData?.sign.signInNum)) {
            setIsCompleted(true);
          }
        }
      }
    );
  }

  const isALlSignined = (signInNum: number) => {
    const checkList = [
      courseStore.courseWatchData.sign1st,
      courseStore.courseWatchData.sign2nd,
      courseStore.courseWatchData.sign3rd
    ].slice(0, courseStore.courseData.sign.signInRule.split(",").length);
    if (signInNum) {
      return checkList.filter(item => !!item).length >= signInNum;
    }
    return checkList.every(item => !!item);
  };

  return {
    isVisible,
    setIsVisible,
    isCompleted,
    setIsCompleted,
    isALlSignined
  };
});

export const useRedPacket = defineStore("RedPacket", () => {
  const courseStore = useCourseData();
  const playerStore = usePlayerStore();
  const isVisible = ref(false);
  const setIsVisible = (value: boolean) => {
    isVisible.value = value;
  };
  const isCompleted = ref(false);
  const setIsCompleted = (value: boolean) => {
    isCompleted.value = value;
  };
  if (true) {
    if (courseStore.courseWatchData?.isAnswer == 1) {
      return;
    }
    watch(
      () => playerStore.maxProgress,
      (maxProgress, oldMaxProgress) => {
        if (maxProgress) {
          if (isVisible.value) {
            return;
          }
          const { redPacket } = courseStore.courseData;
          // 时长红包
          if (redPacket.playType == 0) {
            if (
              redPacket.playTime <= Math.floor(maxProgress) &&
              redPacket.playTime != Math.floor(oldMaxProgress) // 避免触发
            ) {
              if (
                (redPacket.openRedPacket == 2 ||
                  redPacket.openRedPacket == 3) &&
                courseStore.courseWatchData.answerRewardState == 0
              ) {
                // 不需要答题

                if (courseStore.courseData.signInRedPacket == 1) {
                  // 需要签到
                  if (isCompleted.value) {
                    return;
                  }
                  setIsCompleted(true);
                } else {
                  // 不需要签到
                  if (courseStore.courseWatchData.completedRewardState !== 0) {
                    return;
                  }
                  courseStore.reward(2);
                  setIsVisible(true);
                }
              } else {
                // 需要答题或者签到
                if (isCompleted.value) {
                  return;
                }
                setIsCompleted(true);
              }
            }
          }
        }
      }
    );
    watch(
      () => playerStore.isPlayerEnd,
      isEnd => {
        if (isEnd) {
          const { redPacket } = courseStore.courseData;
          // 完播红包
          if (redPacket.playType == 1) {
            if (
              (redPacket.openRedPacket == 2 || redPacket.openRedPacket == 3) &&
              courseStore.courseWatchData.answerRewardState == 0
            ) {
              // 不需要答题

              if (courseStore.courseData.signInRedPacket == 1) {
                // 需要签到
                setIsCompleted(true);
              } else {
                // 不需要签到
                if (courseStore.courseWatchData.completedRewardState !== 0) {
                  return;
                }
                courseStore.reward(2);
                setIsVisible(true);
              }
            } else {
              // 需要答题或者签到
              setIsCompleted(true);
            }
          }
        }
      }
    );
  }
  return {
    isVisible,
    setIsVisible,
    isCompleted
  };
});

export const useQuestion = defineStore("Question", () => {
  const courseStore = useCourseData();
  const playerStore = usePlayerStore();
  const isVisible = ref(false);
  const isCompleted = ref(false);
  const isFailed = ref(false);
  const setIsCompleted = (value: boolean) => {
    isCompleted.value = value;
  };
  const setIsVisible = (value: boolean) => {
    isVisible.value = value;
  };
  const setIsFailed = (value: boolean) => {
    isFailed.value = value;
  };
  // 1/3/4都答题
  if (courseStore.courseWatchData?.isCompleted == 0) {
    // hasAnswerQuestion判断是否完播答题
    if (courseStore.courseData.hasAnswerQuestion == 0) {
      watch(
        () => playerStore.isPlayerEnd,
        value => {
          if (value) {
            if (
              courseStore.courseData.redPacket.openRedPacket == 1 ||
              courseStore.courseData?.redPacket.openRedPacket == 4 ||
              courseStore.courseData?.redPacket.openRedPacket == 3
            ) {
              // courseStore.reward(2);
              setIsVisible(true);
            }
          }
        },
        { once: true }
      );
    } else if (courseStore.courseData.hasAnswerQuestion == 1) {
      // 时长答题
      watch(
        () => playerStore.maxProgress,
        (maxProgress, oldMaxProgress) => {
          if (maxProgress) {
            const newTime = Math.floor(maxProgress);
            const oldTime = Math.floor(oldMaxProgress);

            // 答题次数满足设置的要求
            if (
              courseStore.courseData.answerNum <=
              courseStore.courseWatchData.answerCount
            ) {
              return;
            }

            if (isVisible.value) {
              return;
            }
            // 处理0分钟答题的情况
            if (
              courseStore.courseData.showQuestionTimeLimit == 0 &&
              newTime == 0
            ) {
              setIsVisible(true);
              return;
            }
            // 处理开始答题时间准点的情况
            if (
              courseStore.courseData.showQuestionTimeLimit * 60 == newTime &&
              courseStore.courseData.showQuestionTimeLimit * 60 != oldTime // 避免触发
            ) {
              setIsVisible(true);
              return;
            }

            // 处理当前时间大于开始答题时间点的情况
            if (courseStore.courseData.showQuestionTimeLimit * 60 < newTime) {
              const answerTimeLimit =
                courseStore.courseData.answerTimeLimit * 60; // 答题结束时间
              // 当前时间小于结束时间
              if (
                newTime <
                answerTimeLimit +
                  courseStore.courseData.showQuestionTimeLimit * 60
              ) {
                // 已经答题
                if (courseStore.courseWatchData.isAnswer) {
                  return;
                }
                // 未答题
                setIsVisible(true);
                return;
              } else {
                // 答题时间结束之后
                if (courseStore.courseWatchData.isAnswer) {
                  return;
                }
                // 超时未答题
                courseStore.courseWatchData.answerState = 3;
              }
            }
          }
        }
      );
    }
  } else {
    if (!courseStore.courseWatchData.isAnswer) {
      courseStore.courseWatchData.answerRewardState = 3;
    }
  }
  return {
    isVisible,
    setIsVisible,
    setIsCompleted,
    isCompleted,
    isFailed,
    setIsFailed
  };
});
